package cn.schoolwow.quickdao.module.database.dml.instance.flow.update.flow.updateType;

import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.dml.common.domain.ManipulationOption;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.ArrayList;
import java.util.List;

public class SetPropertyListByUniqueFieldNameFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        setSetPropertyList(flowContext);
        setWherePropertyList(flowContext);
    }

    @Override
    public String name() {
        return "更新实例-设置set和where字段列表-根据指定唯一字段列表";
    }

    private void setSetPropertyList(FlowContext flowContext){
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);
        Entity entity = flowContext.checkData("entity", Entity.class);

        if(!flowContext.containKey("setPropertyList")){
            List<Property> setPropertyList = new ArrayList<>();
            for(Property property:entity.properties){
                if(manipulationOption.uniqueFieldNames.contains(property.name)
                        ||manipulationOption.uniqueFieldNames.contains(property.column)){
                    continue;
                }
                setPropertyList.add(property);
            }
            flowContext.putTemporaryData("setPropertyList", setPropertyList);
        }
    }

    private void setWherePropertyList(FlowContext flowContext){
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);
        Entity entity = flowContext.checkData("entity", Entity.class);

        List<Property> wherePropertyList = new ArrayList<>();
        for(String uniqueFieldName:manipulationOption.uniqueFieldNames){
            Property property = entity.getPropertyByFieldNameOrColumnName(uniqueFieldName);
            if(null==property){
                throw new IllegalArgumentException("指定唯一字段不存在!字段名称:"+uniqueFieldName+",实体类名:"+entity.clazz.getName());
            }
            wherePropertyList.add(property);
        }
        flowContext.putTemporaryData("wherePropertyList", wherePropertyList);
    }
}
